package com.gg.user.controller;

import com.gg.helper.DBHelper;
import com.gg.helper.UUIDHelper;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet(name = "RegistServlet", value = "/user/RegistServlet")
public class RegistServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*1.获取请求参数们  email、 tel、 password */
        String email = request.getParameter("email");
        String  tel = request.getParameter("tel");
        String  password = request.getParameter("password");
        /*需求：新注册的用户，用户名缺省为 邮箱值  */
        /*生成用户名username*/
        String  username = email;
        /*生成uid*/
        String  uid = UUIDHelper.getUUID();

        /*2.规定：1个email只能注册1次，1个tel也只能注册1次
        *   拿着用户的 email 和 tel 去数据库查询，如果已存在则不可注册，反之能注册。
        *
        * String sql = "select *  from  `user` where email = ?  or  tel = ? "
        * */
        /*判定是否已存在*/
        Connection con = DBHelper.getConnection();
        /*SQL*/
        String  sql = "select *  from  `user` where email = ?  or  tel = ? " ;
        /*发射器*/
        try {
            PreparedStatement  ps = con.prepareStatement(sql);
            //在try中继续写
            ps.setString(1,email);
            ps.setString(2,tel);
            //发射
            ResultSet rs = ps.executeQuery();
            if(rs.next()){
                /*已存在！*/
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('Email或者手机号已存在，请核实！！');location.href='/fruit/reg.jsp'</script>");
            }else{
                /*可以注册*/
                sql="insert into  `user` values(?,?,?,?,?)";
                ps=con.prepareStatement(sql);
                ps.setString(1,uid);
                ps.setString(2,username);
                ps.setString(3,password);
                ps.setString(4,tel);
                ps.setString(5,email);
                //发射 插入新记录
                ps.execute();
                //提示用户 恭喜您，请尽快登录，然后跳转到login.jsp登录
                response.setContentType("text/html;charset=utf-8");
                response.getWriter().print("<script>alert('恭喜您，注册成功，请尽快登录！！');location.href='/fruit/login.jsp'</script>");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
